package com.itly.controller;

import com.itly.entity.Admin;
import com.itly.entity.Student;
import com.itly.entity.Teacher;
import com.itly.util.ApiResult;
import com.itly.entity.Login;
import com.itly.service.LoginService;
import com.itly.util.ApiResultHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private LoginService loginService;


    @PostMapping("login")
    public ApiResult login(@RequestBody Login login, HttpServletRequest request) {

        Integer username = login.getUsername();
        String password = login.getPassword();
        Admin adminRes = loginService.adminLogin(username, password);
        if (adminRes != null) {
            logger.info("查询结果为管理员");
            request.getSession().setAttribute("admin", "admin");
            return ApiResultHandler.buildApiResult(200, "请求成功", adminRes);
        }

        Teacher teacherRes = loginService.teacherLogin(username, password);
        if (teacherRes != null) {
            logger.info("查询结果为教师");
            request.getSession().setAttribute("teacher", "teacher");
            return ApiResultHandler.buildApiResult(200, "请求成功", teacherRes);
        }

        Student studentRes = loginService.studentLogin(username, password);
        if (studentRes != null) {
            logger.info("查询结果为学生");
            request.getSession().setAttribute("student", "student");
            return ApiResultHandler.buildApiResult(200, "请求成功", studentRes);
        }

        logger.info("查询结果啥也不是",login);
        return ApiResultHandler.buildApiResult(400, "请求失败", null);
    }

}
